package com.example.index.widget

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Path
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.View
import com.example.index.extension.dp
import com.google.android.flexbox.AlignItems.FLEX_END
import com.google.android.flexbox.FlexboxLayout
import com.google.android.flexbox.JustifyContent.SPACE_AROUND
import com.google.android.flexbox.FlexboxLayout.LayoutParams.WRAP_CONTENT as WRAP_CONTENT1
import com.google.android.flexbox.FlexboxLayout.LayoutParams.WRAP_CONTENT as WRAP_CONTENT2

class ArcTabBar : FlexboxLayout {

    val TAG = "ArcTabBar"
    val paint = Paint(Paint.ANTI_ALIAS_FLAG)
    var pathValid = false
    private var tabs = arrayListOf<SelectableTab>()


    val tabSelectedListener = object : OnClickListener {

        override fun onClick(v: View?) {
            select(tabs.indexOf(v))
        }

    }

    constructor(context: Context?) : this(context, null)
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {

        justifyContent = SPACE_AROUND  //空隙等分
        alignItems = FLEX_END  //底部对齐

        paint.style = Paint.Style.FILL
        paint.color = Color.WHITE

    }

    data class TabParam constructor(
        var text: String, var selectedIconRes: Int, var unselectedIconRes: Int,
        var selectedTextColorRes: Int, var unSelectedTextColorRes: Int,
        var tabTextSizeSp: Float
    )


    fun setTabs(tabList: List<TabParam>) {

        tabList.forEachIndexed { index, it ->
            val selectableTab = SelectableTab(context, it)
            val lp = LayoutParams(WRAP_CONTENT2, WRAP_CONTENT2)
            if (index != tabList.size / 2)
                lp.flexGrow = 1f  //由于中间图标空白部分过大，此时等分间隙会导致左右图标和中间图标空白间距很大，不协调，用grow 属性让左右两边的图标靠近
            addView(selectableTab, lp)
            tabs.add(selectableTab)
            selectableTab.setOnClickListener(tabSelectedListener)
        }
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        pathValid = false

    }


    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        val x = ev.x.toInt()
        val y = ev.y.toInt()


        val centerMenuWidth = getChildAt(childCount / 2).measuredWidth
        val boundaryHeight = measuredHeight - getChildAt(0).measuredHeight - 7.8.dp

        val leftBoundary = measuredWidth / 2 - centerMenuWidth / 2
        val rightBoundary = measuredWidth / 2 + centerMenuWidth / 2

        //顶部透明处则不消费事件，让底层的view 处理
        if ((x in 0..leftBoundary || x in rightBoundary..measuredWidth) && (y in 0..boundaryHeight.toInt()))
            return false

        return super.dispatchTouchEvent(ev)
    }


    /**
     * 绘制贝塞尔曲线
     */
    override fun dispatchDraw(canvas: Canvas?) {
        val smallTab = getChildAt(0)
        val largeTab = getChildAt((childCount + 1) / 2)


        canvas?.drawRect(
            0f, (measuredHeight - smallTab.measuredHeight - 7.8.dp),
            measuredWidth.toFloat(), measuredHeight.toFloat(), paint
        )

//        canvas?.drawPath(createPath(), paint)

        super.dispatchDraw(canvas)
    }

    private fun createPath(): Path {

        val normalTabHeight = getChildAt(0).measuredHeight.toFloat()
        val largeTabHeight = getChildAt((childCount) / 2).measuredHeight.toFloat()
        val largeTabWidth = getChildAt((childCount) / 2).measuredWidth.toFloat()

        Log.i(TAG, "createPath: $normalTabHeight  $largeTabHeight")

        val deltaHeight = measuredHeight - normalTabHeight

        val curX = measuredWidth / 2f - largeTabWidth * 0.75f

        val path = Path()
        path.moveTo(0f, deltaHeight)
        path.lineTo(curX, deltaHeight)
        path.quadTo(
            curX + largeTabWidth * 0.75f * 0.3f,
            deltaHeight * 0.9f,
            measuredWidth / 2f,
            10f
        )

        path.quadTo(
            measuredWidth / 2f + largeTabWidth * 0.75f * 0.7f,
            deltaHeight * 0.9f,
            measuredWidth - curX,
            deltaHeight
        )

        path.lineTo(measuredWidth.toFloat(), deltaHeight)
        path.lineTo(measuredWidth.toFloat(), measuredHeight.toFloat())
        path.lineTo(0f, measuredHeight.toFloat())
        path.lineTo(0f, 0f)
        path.close()

        return path

    }


    fun select(slectIndex: Int) {

        tabs.forEachIndexed { index, selectableTab ->

            if (slectIndex == index)
                selectableTab.select()
            else selectableTab.unselect()
        }

    }
}